package com.goldplusgold.tradedelay.app.my.fragment;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.account.manager.AppCacheSharedPreferences;
import com.example.account.manager.ParmasKey;
import com.goldplusgold.network.lib.AppCollectedInfoUtil;
import com.goldplusgold.network.lib.exception.ServerException;
import com.goldplusgold.support.lib.base.fragment.BaseFragment;
import com.goldplusgold.support.lib.utils.AppInfoUtils;
import com.goldplusgold.support.lib.utils.DeviceNetworkUtil;
import com.goldplusgold.support.lib.utils.FragmentManagerUtil;
import com.goldplusgold.support.lib.utils.NetWorkConstant;
import com.goldplusgold.support.lib.widget.AsyncTask;
import com.goldplusgold.support.lib.wxapi.WeChatUtil;
import com.goldplusgold.support.lib.wxapi.WechatBackMessageEvent;
import com.goldplusgold.tradedelay.app.R;
import com.goldplusgold.tradedelay.app.my.activity.UserActivity;
import com.goldplusgold.tradedelay.app.my.account.AccountCallBack;
import com.goldplusgold.tradedelay.app.my.account.Accountmanager;
import com.goldplusgold.tradedelay.app.my.networkservice.MyService;
import com.goldplusgold.tradedelay.app.my.account.UserInfo;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by Administrator on 2017/5/15.
 */

public class LoginFragment extends BaseFragment implements Handler.Callback {

    @BindView(R.id.et_phone)
    EditText etPhone;
    @BindView(R.id.et_pwd)
    EditText etPwd;
    @BindView(R.id.iv_pwd_status)
    ImageView ivPwdStatus;
    @BindView(R.id.btn_login)
    Button btnLogin;
    @BindView(R.id.btn_forget_pwd)
    TextView btnForgetPwd;
    @BindView(R.id.wechat_login)
    LinearLayout wechatLogin;
    @BindView(R.id.iv_delete_phone)
    ImageView ivDeletePhone;
    private boolean pwdStatus = false;
    private String mUserName;
    private String mPassword;
    private String wechatCode;
    private Handler handler = new Handler(this);

    public static LoginFragment newInstance() {
        Bundle args = new Bundle();
        LoginFragment fragment = new LoginFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_login;
    }


    @Override
    protected void initView() {
        super.initView();
        etPhone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() > 0) {
                    ivDeletePhone.setVisibility(View.VISIBLE);
                } else {
                    ivDeletePhone.setVisibility(View.GONE);
                }
            }
        });
    }


    @OnClick({R.id.iv_back, R.id.iv_delete_phone, R.id.txt_register, R.id.iv_pwd_status, R.id.btn_login, R.id.btn_forget_pwd, R.id.wechat_login})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                if (getActivity() != null && getActivity() instanceof UserActivity) {
                    ((UserActivity) getActivity()).operationAfterLogin();
                }
                break;
            case R.id.iv_delete_phone:
                etPhone.setText("");
                break;
            case R.id.txt_register:
                FragmentManagerUtil.getInstance().openFragment(getActivity(), RegisterFragment.newInstance(), true);
                break;
            case R.id.iv_pwd_status:
                if (pwdStatus) {
                    pwdStatus = false;
                    etPwd.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                    ivPwdStatus.setSelected(false);
                } else {
                    pwdStatus = true;
                    etPwd.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                    ivPwdStatus.setSelected(true);
                }
                break;
            case R.id.btn_login:
                mUserName = etPhone.getText().toString().trim();
                mPassword = etPwd.getText().toString().trim();
                if (TextUtils.isEmpty(mUserName)) {
                    showToastMessage(getActivity().getString(R.string.please_enter_phone_number), Toast.LENGTH_SHORT);
                    return;
                }
                if (TextUtils.isEmpty(mPassword)) {
                    showToastMessage(getActivity().getString(R.string.please_enter_pwd), Toast.LENGTH_SHORT);
                    return;
                }
                Accountmanager.Login(getActivity(), mUserName, mPassword, new AccountCallBack<UserInfo>() {
                    @Override
                    public void success(UserInfo userInfo) {
                        String token = userInfo.getToken();
                        String time = String.valueOf(System.currentTimeMillis());
                        String versionName = AppInfoUtils.getVersionName(getActivity());
                        AppCacheSharedPreferences.putCacheString(ParmasKey.token , token);
                        AppCacheSharedPreferences.putCacheString(ParmasKey.user_name , userInfo.getUserName());
                        AppCacheSharedPreferences.putCacheBoolean(ParmasKey.login_state , true);
                        AppCacheSharedPreferences.putCacheString(ParmasKey.headImage , userInfo.getHeadImage());
                        AppCollectedInfoUtil.initAppCollectedInfo(getActivity(), token, time, versionName);
                        getActivity().setResult(Activity.RESULT_OK);
                        finishActivity();
                    }

                    @Override
                    public void fail(Exception e) {
                        showToastMessage(e.getMessage() , Toast.LENGTH_SHORT);
                    }
                });
                //String imei = DeviceNetworkUtil.getIMEIWrap(getContext());
                //new LoginAsyncTask(imei).execute(AsyncTask.TYPE_NET);
                break;
            case R.id.btn_forget_pwd:
                FragmentManagerUtil.getInstance().openFragment(getActivity(), ForgotPasswordFragment.newInstance(1, "请使用您注册的手机号码找回登录密码", "下一步", ""), true);
                break;
            case R.id.wechat_login:
                wechatLogin.setEnabled(false);
                WeChatUtil.getInstance().WXLogin();
                break;
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        wechatLogin.setEnabled(true);
    }

    @Override
    public boolean handleMessage(Message msg) {
        int type = msg.what;
        switch (type) {
            case NetWorkConstant.NETWORK_ERROR_CODE:
                showToastMessage(R.string.network_error, Toast.LENGTH_LONG);
                break;
            case NetWorkConstant.NETWORK_SERVER_ERROR_CODE:
                String errorMessage = (String) msg.obj;
                showToastMessage(errorMessage, Toast.LENGTH_LONG);
                break;

        }

        return true;
    }


    public class LoginAsyncTask extends AsyncTask<Void, Void, UserInfo> {
        private String imei;

        public LoginAsyncTask(String imei) {
            this.imei = imei;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            showLoadingControl();
        }

        @Override
        protected UserInfo doInBackground(Void... params) {
            UserInfo userInfo = null;
            try {
                userInfo = MyService.getInstance().userLogin("android", mUserName, mPassword, "android", imei);
            } catch (ServerException e) {
                e.printStackTrace();
                sendNetworkErrorMessage(NetWorkConstant.NETWORK_SERVER_ERROR_CODE, e.getMessage());
            } catch (Exception e) {
                e.printStackTrace();
                sendNetworkErrorMessage(NetWorkConstant.NETWORK_ERROR_CODE, null);
            }
            return userInfo;
        }

        @Override
        protected void onPostExecute(UserInfo userInfo) {
            super.onPostExecute(userInfo);
            dismisLoadingControl();
            if (userInfo != null) {
                String token = userInfo.getToken();
                String time = String.valueOf(System.currentTimeMillis());
                String versionName = AppInfoUtils.getVersionName(getActivity());
                AppCollectedInfoUtil.initAppCollectedInfo(getActivity(), token, time, versionName);
                if (getActivity() == null && getActivity().isFinishing()) {
                    return;
                }
                getActivity().setResult(Activity.RESULT_OK);
                if (getActivity() instanceof UserActivity) {
                    ((UserActivity) getActivity()).operationAfterLogin();
                }
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onWechatBackEvent(WechatBackMessageEvent event) {
        wechatCode = event.getCode();
        String imei = DeviceNetworkUtil.getIMEIWrap(getContext());
        new WechatLoginAsyncTask(imei).execute(AsyncTask.TYPE_NET);
    }

    private void sendNetworkErrorMessage(int type, String errorMessage) {
        Message message = handler.obtainMessage();
        message.what = type;
        if (!TextUtils.isEmpty(errorMessage)) {
            message.obj = errorMessage;
        }
        handler.sendMessage(message);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    public class WechatLoginAsyncTask extends AsyncTask<Void, Void, UserInfo> {
        String imei;

        public WechatLoginAsyncTask(String imei) {
            this.imei = imei;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            showLoadingControl();
        }

        @Override
        protected UserInfo doInBackground(Void... params) {
            try {

                UserInfo userInfo = MyService.getInstance().wechatLogin("android", wechatCode, "android", imei);
                if (userInfo != null) {
                    return userInfo;
                }
            } catch (ServerException e) {

                sendNetworkErrorMessage(NetWorkConstant.NETWORK_SERVER_ERROR_CODE, e.getMessage());

            } catch (Exception e) {
                e.printStackTrace();
                sendNetworkErrorMessage(NetWorkConstant.NETWORK_ERROR_CODE, null);
            }

            return null;
        }

        @Override
        protected void onPostExecute(UserInfo userInfo) {
            super.onPostExecute(userInfo);
            dismisLoadingControl();
            if (userInfo != null) {
                if (userInfo.getStatus()) {
                    String token = userInfo.getToken();
                    String time = String.valueOf(System.currentTimeMillis());
                    String versionName = AppInfoUtils.getVersionName(getActivity());
                    AppCollectedInfoUtil.initAppCollectedInfo(getActivity(), token, time, versionName);
                    getActivity().setResult(Activity.RESULT_OK);
                    finishActivity();
                } else {
                    FragmentManagerUtil.getInstance().openFragment(getActivity(), ForgotPasswordFragment.newInstance(2, "绑定手机号，便于下次快捷登录", "确认", wechatCode), true);
                }
            }

        }

    }

}
